package com.xy.netty.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;


/**
 * @author xy
 */
public class HttpServerHandler extends SimpleChannelInboundHandler<HttpRequest> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpRequest httpRequest) throws Exception {
        //1.判断是不是http请求
        if (httpRequest instanceof HttpRequest) {
            System.out.println("msg类型：" + httpRequest.getClass());
            System.out.println("客户端地址：" + ctx.channel().remoteAddress());
            //2.回复信息给浏览器[http协议]
            ByteBuf httpReturnContent = Unpooled.copiedBuffer("hello,I'm xy", CharsetUtil.UTF_8);
            //3.构建http相应
            DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, httpReturnContent);
            response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH, httpReturnContent.readableBytes());
            ctx.writeAndFlush(response);
        }
    }
}
